package com.principles.behavior.memento;

import java.util.Stack;

/**
 * @Description 备忘录模式：允许在不暴露对象实现细节的情况下保存和恢复对象之前的状态
 * @Date 2025/1/30 21:20
 **/
public class MementoPattern {
    public static void main(String[] args) {
        History history = new History();
        Document document = new Document();
        document.change("abd");
        history.add(document.save());

        document.change("123");
        history.add(document.save());

        document.change("aasd87");
        history.add(document.save());

        document.resume( history.getLastVersion());
        document.print();
        document.resume( history.getLastVersion());
        document.print();
    }
}

// 备忘录接口
interface Memento {

}
// 文档类
class Document{
    private String content;

    public BackUp save(){
        return new BackUp(content);
    }
    public void resume(BackUp backUp){
        content = backUp.content;
    }
    public void change(String content){
        this.content = content;
    }
    public void print(){
        System.out.println(content);
    }
}

// 备忘录类
class BackUp implements Memento{
    String content;
    public BackUp (String content){
        this.content = content;
    }
}

// 备忘录栈
class History{
    Stack<BackUp> backUpStack = new Stack<>();
    public void add(BackUp backUp){
        backUpStack.add(backUp);
    }
    public BackUp getLastVersion(){
        return backUpStack.pop();
    }
}